﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace thinger.AutomaticStoreMotionDAL
{
    public class IniConfigHelper
    {
        #region API函数申明
        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        #endregion

        #region Ini文件路径
        private static string _filePath = string.Empty;
        #endregion

        #region 读取INI文件
        public static string ReadIniData(string section, string key, string noText)
        {
            return ReadIniData(section, key, noText, _filePath);
        }
        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="section">段名</param>
        /// <param name="key">键名</param>
        /// <param name="noText">无效默认值</param>
        /// <returns>键值</returns>
        public static string ReadIniData(string section, string key, string noText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(section, key, noText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return string.Empty;
            }

        }
        #endregion

        #region 写入Ini文件
        public static bool WriteIniData(string section, string key, string value)
        {
            return WriteIniData(section, key, value, _filePath);
        }
        public static bool WriteIniData(string section, string key, string value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(section, key, value, iniFilePath);
                if (OpStation == 0)
                {
                    return false;
                }
                else { return true; }
            }
            else { return false; }
        }

        #endregion

    }
}
